<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>分类: 技术教程 | 小小程序员</title><meta name="author" content="十一星野"><meta name="copyright" content="十一星野"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="平时在开发接口的时候，常常会需要对参数进行校验，这里提供两种处理校验逻辑的方式。一种是使用 Hibernate Validator 来处理，另一种是使用全局异常来处理，下面我们讲下这两种方式的用法。  #👍 相关视频教程 SpringBoot中处理校验逻辑的两种方式_上篇open in new window SpringBoot中处理校验逻辑的两种方式_下篇open in new window">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot中处理校验逻辑的两种方式，真的很机智！">
<meta property="og:url" content="https://ko25891wan.gitlab.io/2024/01/94dcc9008f8c.html">
<meta property="og:site_name" content="小小程序员">
<meta property="og:description" content="平时在开发接口的时候，常常会需要对参数进行校验，这里提供两种处理校验逻辑的方式。一种是使用 Hibernate Validator 来处理，另一种是使用全局异常来处理，下面我们讲下这两种方式的用法。  #👍 相关视频教程 SpringBoot中处理校验逻辑的两种方式_上篇open in new window SpringBoot中处理校验逻辑的两种方式_下篇open in new window">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png">
<meta property="article:published_time" content="2024-01-21T09:28:10.000Z">
<meta property="article:modified_time" content="2024-02-02T14:52:49.775Z">
<meta property="article:author" content="十一星野">
<meta property="article:tag" content="宅男,热血">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://ko25891wan.gitlab.io/2024/01/94dcc9008f8c.html"><link rel="preconnect" href="//fastly.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.5.1/css/all.min.css"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":1,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.staticfile.org/egjs-infinitegrid/4.11.0/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '分类: 技术教程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-02-02 22:52:49'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="小小程序员"><span class="site-name">小小程序员</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">SpringBoot中处理校验逻辑的两种方式，真的很机智！</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-01-21T09:28:10.000Z" title="发表于 2024-01-21 17:28:10">2024-01-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-02-02T14:52:49.775Z" title="更新于 2024-02-02 22:52:49">2024-02-02</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/">技术教程</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/">mall</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/%E6%8A%80%E6%9C%AF%E8%A6%81%E7%82%B9%E7%AF%87/">技术要点篇</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="SpringBoot中处理校验逻辑的两种方式，真的很机智！"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><blockquote>
<p>平时在开发接口的时候，常常会需要对参数进行校验，这里提供两种处理校验逻辑的方式。一种是使用 Hibernate Validator 来处理，另一种是使用全局异常来处理，下面我们讲下这两种方式的用法。</p>
</blockquote>
<h2 id="👍-相关视频教程"><a href="#👍-相关视频教程" class="headerlink" title="#👍 相关视频教程"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%F0%9F%91%8D-%E7%9B%B8%E5%85%B3%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B">#</a>👍 相关视频教程</h2><ul>
<li><a target="_blank" rel="noopener" href="https://t.zsxq.com/0ejeli5SF">SpringBoot中处理校验逻辑的两种方式_上篇open in new window</a></li>
<li><a target="_blank" rel="noopener" href="https://t.zsxq.com/0eB7ljwzc">SpringBoot中处理校验逻辑的两种方式_下篇open in new window</a></li>
</ul>
<h2 id="Hibernate-Validator"><a href="#Hibernate-Validator" class="headerlink" title="#Hibernate Validator"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#hibernate-validator">#</a>Hibernate Validator</h2><blockquote>
<p>Hibernate Validator是SpringBoot内置的校验框架，只要集成了SpringBoot就自动集成了它，我们可以通过在对象上面使用它提供的注解来完成参数校验。</p>
</blockquote>
<h3 id="常用注解"><a href="#常用注解" class="headerlink" title="#常用注解"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3">#</a>常用注解</h3><blockquote>
<p>我们先来了解下常用的注解，对Hibernate Validator所提供的校验功能有个印象。</p>
</blockquote>
<ul>
<li>@Null：被注释的属性必须为null；</li>
<li>@NotNull：被注释的属性不能为null；</li>
<li>@AssertTrue：被注释的属性必须为true；</li>
<li>@AssertFalse：被注释的属性必须为false；</li>
<li>@Min：被注释的属性必须大于等于其value值；</li>
<li>@Max：被注释的属性必须小于等于其value值；</li>
<li>@Size：被注释的属性必须在其min和max值之间；</li>
<li>@Pattern：被注释的属性必须符合其regexp所定义的正则表达式；</li>
<li>@NotBlank：被注释的字符串不能为空字符串；</li>
<li>@NotEmpty：被注释的属性不能为空；</li>
<li>@Email：被注释的属性必须符合邮箱格式。</li>
</ul>
<h3 id="使用方式"><a href="#使用方式" class="headerlink" title="#使用方式"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F">#</a>使用方式</h3><blockquote>
<p>接下来我们以添加品牌接口的参数校验为例来讲解下Hibernate Validator的使用方法，其中涉及到一些AOP的知识，不了解的朋友可以参考下<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/mNujRjejQ1bITveFI6gkcg">《SpringBoot应用中使用AOP记录接口访问日志》open in new window</a>。</p>
</blockquote>
<ul>
<li>首先我们需要在添加品牌接口的参数<code>PmsBrandParam</code>中添加校验注解，用于确定属性的校验规则及校验失败后需要返回的信息；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 品牌传递参数</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">public class PmsBrandParam &#123;</span><br><span class="line">    @ApiModelProperty(value = &quot;品牌名称&quot;,required = true)</span><br><span class="line">    @NotEmpty(message = &quot;名称不能为空&quot;)</span><br><span class="line">    private String name;</span><br><span class="line">    @ApiModelProperty(value = &quot;品牌首字母&quot;)</span><br><span class="line">    private String firstLetter;</span><br><span class="line">    @ApiModelProperty(value = &quot;排序字段&quot;)</span><br><span class="line">    @Min(value = 0, message = &quot;排序最小为0&quot;)</span><br><span class="line">    private Integer sort;</span><br><span class="line">    @ApiModelProperty(value = &quot;是否为厂家制造商&quot;)</span><br><span class="line">    @FlagValidator(value = &#123;&quot;0&quot;,&quot;1&quot;&#125;, message = &quot;厂家状态不正确&quot;)</span><br><span class="line">    private Integer factoryStatus;</span><br><span class="line">    @ApiModelProperty(value = &quot;是否进行显示&quot;)</span><br><span class="line">    @FlagValidator(value = &#123;&quot;0&quot;,&quot;1&quot;&#125;, message = &quot;显示状态不正确&quot;)</span><br><span class="line">    private Integer showStatus;</span><br><span class="line">    @ApiModelProperty(value = &quot;品牌logo&quot;,required = true)</span><br><span class="line">    @NotEmpty(message = &quot;品牌logo不能为空&quot;)</span><br><span class="line">    private String logo;</span><br><span class="line">    @ApiModelProperty(value = &quot;品牌大图&quot;)</span><br><span class="line">    private String bigPic;</span><br><span class="line">    @ApiModelProperty(value = &quot;品牌故事&quot;)</span><br><span class="line">    private String brandStory;</span><br><span class="line"></span><br><span class="line">   //省略若干Getter和Setter方法...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在添加品牌的接口中添加@Validated注解，并注入一个BindingResult参数；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 品牌功能Controller</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">@Controller</span><br><span class="line">@Api(tags = &quot;PmsBrandController&quot;, description = &quot;商品品牌管理&quot;)</span><br><span class="line">@RequestMapping(&quot;/brand&quot;)</span><br><span class="line">public class PmsBrandController &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private PmsBrandService brandService;</span><br><span class="line"></span><br><span class="line">    @ApiOperation(value = &quot;添加品牌&quot;)</span><br><span class="line">    @RequestMapping(value = &quot;/create&quot;, method = RequestMethod.POST)</span><br><span class="line">    @ResponseBody</span><br><span class="line">    public CommonResult create(@Validated @RequestBody PmsBrandParam pmsBrand, BindingResult result) &#123;</span><br><span class="line">        CommonResult commonResult;</span><br><span class="line">        int count = brandService.createBrand(pmsBrand);</span><br><span class="line">        if (count == 1) &#123;</span><br><span class="line">            commonResult = CommonResult.success(count);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            commonResult = CommonResult.failed();</span><br><span class="line">        &#125;</span><br><span class="line">        return commonResult;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在整个Controller层创建一个切面，在其环绕通知中获取到注入的BindingResult对象，通过hasErrors方法判断校验是否通过，如果有错误信息直接返回错误信息，验证通过则放行；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * HibernateValidator错误结果处理切面</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">@Aspect</span><br><span class="line">@Component</span><br><span class="line">@Order(2)</span><br><span class="line">public class BindingResultAspect &#123;</span><br><span class="line">    @Pointcut(&quot;execution(public * com.macro.mall.controller.*.*(..))&quot;)</span><br><span class="line">    public void BindingResult() &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Around(&quot;BindingResult()&quot;)</span><br><span class="line">    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable &#123;</span><br><span class="line">        Object[] args = joinPoint.getArgs();</span><br><span class="line">        for (Object arg : args) &#123;</span><br><span class="line">            if (arg instanceof BindingResult) &#123;</span><br><span class="line">                BindingResult result = (BindingResult) arg;</span><br><span class="line">                if (result.hasErrors()) &#123;</span><br><span class="line">                    FieldError fieldError = result.getFieldError();</span><br><span class="line">                    if(fieldError!=null)&#123;</span><br><span class="line">                        return CommonResult.validateFailed(fieldError.getDefaultMessage());</span><br><span class="line">                    &#125;else&#123;</span><br><span class="line">                        return CommonResult.validateFailed();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return joinPoint.proceed();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>此时我们访问添加品牌的接口，不传入<code>name</code>字段，就会返回<code>名称不能为空</code>的错误信息；</li>
</ul>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/2024-02-02_22:52:43_springboot_validator_01-d3a89c23.png"></p>
<ul>
<li>使用切面的话，由于每个校验方法中都需要注入<code>BindingResult</code>对象，这样会导致很多重复工作，其实当校验失败时，SpringBoot默认会抛出<code>MethodArgumentNotValidException</code>或<code>BindException</code>异常，我们只要全局处理该异常依然可以得到校验失败信息。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 全局异常处理</span><br><span class="line"> * Created by macro on 2020/2/27.</span><br><span class="line"> */</span><br><span class="line">@ControllerAdvice</span><br><span class="line">public class GlobalExceptionHandler &#123;</span><br><span class="line">    </span><br><span class="line">   @ResponseBody</span><br><span class="line">   @ExceptionHandler(value = MethodArgumentNotValidException.class)</span><br><span class="line">   public R handleValidException(MethodArgumentNotValidException e) &#123;</span><br><span class="line">       BindingResult bindingResult = e.getBindingResult();</span><br><span class="line">       String message = null;</span><br><span class="line">       if (bindingResult.hasErrors()) &#123;</span><br><span class="line">           FieldError fieldError = bindingResult.getFieldError();</span><br><span class="line">           if (fieldError != null) &#123;</span><br><span class="line">               message = fieldError.getField()+fieldError.getDefaultMessage();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       return CommonResult.failed(message);</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">    @ResponseBody</span><br><span class="line">    @ExceptionHandler(value = BindException.class)</span><br><span class="line">    public R handleValidException(BindException e) &#123;</span><br><span class="line">        BindingResult bindingResult = e.getBindingResult();</span><br><span class="line">        String message = null;</span><br><span class="line">        if (bindingResult.hasErrors()) &#123;</span><br><span class="line">            FieldError fieldError = bindingResult.getFieldError();</span><br><span class="line">            if (fieldError != null) &#123;</span><br><span class="line">                message = fieldError.getField()+fieldError.getDefaultMessage();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return Response.failed(message);</span><br><span class="line">    &#125;   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>由于SpringBoot 2.3版本默认移除了校验功能，如果想要开启的话需要添加如下依赖。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<h3 id="自定义注解"><a href="#自定义注解" class="headerlink" title="#自定义注解"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3">#</a>自定义注解</h3><blockquote>
<p>有时候框架提供的校验注解并不能满足我们的需要，此时我们就需要自定义校验注解。比如还是上面的添加品牌，此时有个参数<code>showStatus</code>，我们希望它只能是0或者1，不能是其他数字，此时可以使用自定义注解来实现该功能。</p>
</blockquote>
<ul>
<li>首先自定义一个校验注解类FlagValidator，然后添加@Constraint注解，使用它的validatedBy属性指定校验逻辑的具体实现类；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 用户验证状态是否在指定范围内的注解</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">@Documented</span><br><span class="line">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="line">@Target(&#123;ElementType.FIELD,ElementType.PARAMETER&#125;)</span><br><span class="line">@Constraint(validatedBy = FlagValidatorClass.class)</span><br><span class="line">public @interface FlagValidator &#123;</span><br><span class="line">    String[] value() default &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    String message() default &quot;flag is not found&quot;;</span><br><span class="line"></span><br><span class="line">    Class&lt;?&gt;[] groups() default &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    Class&lt;? extends Payload&gt;[] payload() default &#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后创建FlagValidatorClass作为校验逻辑的具体实现类，实现ConstraintValidator接口，这里需要指定两个泛型参数，第一个需要指定为你自定义的校验注解类，第二个指定为你要校验属性的类型，isValid方法中就是具体的校验逻辑。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 状态标记校验器</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">public class FlagValidatorClass implements ConstraintValidator&lt;FlagValidator,Integer&gt; &#123;</span><br><span class="line">    private String[] values;</span><br><span class="line">    @Override</span><br><span class="line">    public void initialize(FlagValidator flagValidator) &#123;</span><br><span class="line">        this.values = flagValidator.value();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) &#123;</span><br><span class="line">        boolean isValid = false;</span><br><span class="line">        if(value==null)&#123;</span><br><span class="line">            //当状态为空时使用默认值</span><br><span class="line">            return true;</span><br><span class="line">        &#125;</span><br><span class="line">        for(int i=0;i&lt;values.length;i++)&#123;</span><br><span class="line">            if(values[i].equals(String.valueOf(value)))&#123;</span><br><span class="line">                isValid = true;</span><br><span class="line">                break;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return isValid;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>接下来我们就可以在传参对象中使用该注解了；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 品牌传递参数</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">public class PmsBrandParam &#123;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;是否进行显示&quot;)</span><br><span class="line">    @FlagValidator(value = &#123;&quot;0&quot;,&quot;1&quot;&#125;, message = &quot;显示状态不正确&quot;)</span><br><span class="line">    private Integer showStatus;</span><br><span class="line"></span><br><span class="line">   //省略若干Getter和Setter方法...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>最后我们测试下该注解，调用接口是传入<code>showStatus=3</code>，会返回<code>显示状态不正确</code>的错误信息。</li>
</ul>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/2024-02-02_22:52:43_springboot_validator_02-9311a185.png"></p>
<h3 id="优缺点"><a href="#优缺点" class="headerlink" title="#优缺点"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%E4%BC%98%E7%BC%BA%E7%82%B9">#</a>优缺点</h3><p>这种方式的优点是可以使用注解来实现参数校验，不需要一些重复的校验逻辑，但是也有一些缺点，比如需要在Controller的方法中额外注入一个BindingResult对象，只支持一些简单的校验，涉及到要查询数据库的校验就无法满足了。</p>
<h2 id="全局异常处理"><a href="#全局异常处理" class="headerlink" title="#全局异常处理"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%E5%85%A8%E5%B1%80%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86">#</a>全局异常处理</h2><blockquote>
<p>使用全局异常处理来处理校验逻辑的思路很简单，首先我们需要通过@ControllerAdvice注解定义一个全局异常的处理类，然后自定义一个校验异常，当我们在Controller中校验失败时，直接抛出该异常，这样就可以达到校验失败返回错误信息的目的了。</p>
</blockquote>
<h3 id="使用到的注解"><a href="#使用到的注解" class="headerlink" title="#使用到的注解"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%E4%BD%BF%E7%94%A8%E5%88%B0%E7%9A%84%E6%B3%A8%E8%A7%A3">#</a>使用到的注解</h3><p>@ControllerAdvice：类似于@Component注解，可以指定一个组件，这个组件主要用于增强@Controller注解修饰的类的功能，比如说进行全局异常处理。</p>
<p>@ExceptionHandler：用来修饰全局异常处理的方法，可以指定异常的类型。</p>
<h3 id="使用方式-1"><a href="#使用方式-1" class="headerlink" title="#使用方式"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-1">#</a>使用方式</h3><ul>
<li>首先我们需要自定义一个异常类<code>ApiException</code>，当我们校验失败时抛出该异常：</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义API异常</span><br><span class="line"> * Created by macro on 2020/2/27.</span><br><span class="line"> */</span><br><span class="line">public class ApiException extends RuntimeException &#123;</span><br><span class="line">    private IErrorCode errorCode;</span><br><span class="line"></span><br><span class="line">    public ApiException(IErrorCode errorCode) &#123;</span><br><span class="line">        super(errorCode.getMessage());</span><br><span class="line">        this.errorCode = errorCode;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public ApiException(String message) &#123;</span><br><span class="line">        super(message);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public ApiException(Throwable cause) &#123;</span><br><span class="line">        super(cause);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public ApiException(String message, Throwable cause) &#123;</span><br><span class="line">        super(message, cause);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public IErrorCode getErrorCode() &#123;</span><br><span class="line">        return errorCode;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后创建一个断言处理类<code>Asserts</code>，用于抛出各种<code>ApiException</code>；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 断言处理类，用于抛出各种API异常</span><br><span class="line"> * Created by macro on 2020/2/27.</span><br><span class="line"> */</span><br><span class="line">public class Asserts &#123;</span><br><span class="line">    public static void fail(String message) &#123;</span><br><span class="line">        throw new ApiException(message);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static void fail(IErrorCode errorCode) &#123;</span><br><span class="line">        throw new ApiException(errorCode);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后再创建我们的全局异常处理类<code>GlobalExceptionHandler</code>，用于处理全局异常，并返回封装好的CommonResult对象；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 全局异常处理</span><br><span class="line"> * Created by macro on 2020/2/27.</span><br><span class="line"> */</span><br><span class="line">@ControllerAdvice</span><br><span class="line">public class GlobalExceptionHandler &#123;</span><br><span class="line"></span><br><span class="line">    @ResponseBody</span><br><span class="line">    @ExceptionHandler(value = ApiException.class)</span><br><span class="line">    public CommonResult handle(ApiException e) &#123;</span><br><span class="line">        if (e.getErrorCode() != null) &#123;</span><br><span class="line">            return CommonResult.failed(e.getErrorCode());</span><br><span class="line">        &#125;</span><br><span class="line">        return CommonResult.failed(e.getMessage());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>这里拿用户领取优惠券的代码为例，我们先对比下改进前后的代码，首先看Controller层代码。改进后只要Service中的方法执行成功就表示领取优惠券成功，因为领取不成功的话会直接抛出ApiException从而返回错误信息；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 用户优惠券管理Controller</span><br><span class="line"> * Created by macro on 2018/8/29.</span><br><span class="line"> */</span><br><span class="line">@Controller</span><br><span class="line">@Api(tags = &quot;UmsMemberCouponController&quot;, description = &quot;用户优惠券管理&quot;)</span><br><span class="line">@RequestMapping(&quot;/member/coupon&quot;)</span><br><span class="line">public class UmsMemberCouponController &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private UmsMemberCouponService memberCouponService;</span><br><span class="line">    </span><br><span class="line">    //改进前</span><br><span class="line">    @ApiOperation(&quot;领取指定优惠券&quot;)</span><br><span class="line">    @RequestMapping(value = &quot;/add/&#123;couponId&#125;&quot;, method = RequestMethod.POST)</span><br><span class="line">    @ResponseBody</span><br><span class="line">    public CommonResult add(@PathVariable Long couponId) &#123;</span><br><span class="line">        return memberCouponService.add(couponId);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    //改进后</span><br><span class="line">    @ApiOperation(&quot;领取指定优惠券&quot;)</span><br><span class="line">    @RequestMapping(value = &quot;/add/&#123;couponId&#125;&quot;, method = RequestMethod.POST)</span><br><span class="line">    @ResponseBody</span><br><span class="line">    public CommonResult add(@PathVariable Long couponId) &#123;</span><br><span class="line">        memberCouponService.add(couponId);</span><br><span class="line">        return CommonResult.success(null,&quot;领取成功&quot;);</span><br><span class="line">    &#125;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>再看下Service接口中的代码，区别在于返回结果，改进后返回的是void。其实CommonResult的作用本来就是为了把Service中获取到的数据封装成统一返回结果，改进前的做法违背了这个原则，改进后的做法解决了这个问题；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 用户优惠券管理Service</span><br><span class="line"> * Created by macro on 2018/8/29.</span><br><span class="line"> */</span><br><span class="line">public interface UmsMemberCouponService &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 会员添加优惠券（改进前）</span><br><span class="line">     */</span><br><span class="line">    @Transactional</span><br><span class="line">    CommonResult add(Long couponId);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 会员添加优惠券（改进后）</span><br><span class="line">     */</span><br><span class="line">    @Transactional</span><br><span class="line">    void add(Long couponId);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>再看下Service实现类中的代码，可以看到原先校验逻辑中返回CommonResult的逻辑都改成了调用Asserts的fail方法来实现；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 会员优惠券管理Service实现类</span><br><span class="line"> * Created by macro on 2018/8/29.</span><br><span class="line"> */</span><br><span class="line">@Service</span><br><span class="line">public class UmsMemberCouponServiceImpl implements UmsMemberCouponService &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private UmsMemberService memberService;</span><br><span class="line">    @Autowired</span><br><span class="line">    private SmsCouponMapper couponMapper;</span><br><span class="line">    @Autowired</span><br><span class="line">    private SmsCouponHistoryMapper couponHistoryMapper;</span><br><span class="line">    @Autowired</span><br><span class="line">    private SmsCouponHistoryDao couponHistoryDao;</span><br><span class="line">    </span><br><span class="line">    //改进前</span><br><span class="line">    @Override</span><br><span class="line">    public CommonResult add(Long couponId) &#123;</span><br><span class="line">        UmsMember currentMember = memberService.getCurrentMember();</span><br><span class="line">        //获取优惠券信息，判断数量</span><br><span class="line">        SmsCoupon coupon = couponMapper.selectByPrimaryKey(couponId);</span><br><span class="line">        if(coupon==null)&#123;</span><br><span class="line">            return CommonResult.failed(&quot;优惠券不存在&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        if(coupon.getCount()&lt;=0)&#123;</span><br><span class="line">            return CommonResult.failed(&quot;优惠券已经领完了&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        Date now = new Date();</span><br><span class="line">        if(now.before(coupon.getEnableTime()))&#123;</span><br><span class="line">            return CommonResult.failed(&quot;优惠券还没到领取时间&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        //判断用户领取的优惠券数量是否超过限制</span><br><span class="line">        SmsCouponHistoryExample couponHistoryExample = new SmsCouponHistoryExample();</span><br><span class="line">        couponHistoryExample.createCriteria().andCouponIdEqualTo(couponId).andMemberIdEqualTo(currentMember.getId());</span><br><span class="line">        long count = couponHistoryMapper.countByExample(couponHistoryExample);</span><br><span class="line">        if(count&gt;=coupon.getPerLimit())&#123;</span><br><span class="line">            return CommonResult.failed(&quot;您已经领取过该优惠券&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        //省略领取优惠券逻辑...</span><br><span class="line">        return CommonResult.success(null,&quot;领取成功&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    //改进后</span><br><span class="line">     @Override</span><br><span class="line">     public void add(Long couponId) &#123;</span><br><span class="line">         UmsMember currentMember = memberService.getCurrentMember();</span><br><span class="line">         //获取优惠券信息，判断数量</span><br><span class="line">         SmsCoupon coupon = couponMapper.selectByPrimaryKey(couponId);</span><br><span class="line">         if(coupon==null)&#123;</span><br><span class="line">             Asserts.fail(&quot;优惠券不存在&quot;);</span><br><span class="line">         &#125;</span><br><span class="line">         if(coupon.getCount()&lt;=0)&#123;</span><br><span class="line">             Asserts.fail(&quot;优惠券已经领完了&quot;);</span><br><span class="line">         &#125;</span><br><span class="line">         Date now = new Date();</span><br><span class="line">         if(now.before(coupon.getEnableTime()))&#123;</span><br><span class="line">             Asserts.fail(&quot;优惠券还没到领取时间&quot;);</span><br><span class="line">         &#125;</span><br><span class="line">         //判断用户领取的优惠券数量是否超过限制</span><br><span class="line">         SmsCouponHistoryExample couponHistoryExample = new SmsCouponHistoryExample();</span><br><span class="line">         couponHistoryExample.createCriteria().andCouponIdEqualTo(couponId).andMemberIdEqualTo(currentMember.getId());</span><br><span class="line">         long count = couponHistoryMapper.countByExample(couponHistoryExample);</span><br><span class="line">         if(count&gt;=coupon.getPerLimit())&#123;</span><br><span class="line">             Asserts.fail(&quot;您已经领取过该优惠券&quot;);</span><br><span class="line">         &#125;</span><br><span class="line">         //省略领取优惠券逻辑...</span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>这里我们输入一个没有的优惠券ID来测试下该功能，会返回<code>优惠券不存在</code>的错误信息。</li>
</ul>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/2024-02-02_22:52:43_springboot_validator_03-6d6c82bf.png"></p>
<h3 id="优缺点-1"><a href="#优缺点-1" class="headerlink" title="#优缺点"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%E4%BC%98%E7%BC%BA%E7%82%B9-1">#</a>优缺点</h3><p>使用全局异常来处理校验逻辑的优点是比较灵活，可以处理复杂的校验逻辑。缺点是我们需要重复编写校验代码，不像使用Hibernate Validator那样只要使用注解就可以了。不过我们可以在上面的<code>Asserts</code>类中添加一些工具方法来增强它的功能，比如判断是否为空和判断长度等都可以自己实现。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="#总结"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%E6%80%BB%E7%BB%93">#</a>总结</h2><p>我们可以两种方法一起结合使用，比如简单的参数校验使用Hibernate Validator来实现，而一些涉及到数据库操作的复杂校验使用全局异常处理的方式来实现。</p>
<h2 id="项目源码地址"><a href="#项目源码地址" class="headerlink" title="#项目源码地址"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/technology/springboot_validator.html#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80">#</a>项目源码地址</h2><p><a target="_blank" rel="noopener" href="https://github.com/macrozheng/mall">https://github.com/macrozheng/mall</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io">十一星野</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io/2024/01/94dcc9008f8c.html">https://ko25891wan.gitlab.io/2024/01/94dcc9008f8c.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://ko25891wan.gitlab.io" target="_blank">小小程序员</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2024/01/6e44f3117e70.html" title="不要再重复造轮子了，这款开源工具类库贼好使！"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">不要再重复造轮子了，这款开源工具类库贼好使！</div></div></a></div><div class="next-post pull-right"><a href="/2024/01/cd1563ab1e3d.html" title="SpringBoot应用中使用AOP记录接口访问日志"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">SpringBoot应用中使用AOP记录接口访问日志</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">十一星野</div><div class="author-info__description">归途也还可爱</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Gitlab"><i class="fab fa-gitlab" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:ko25891wan@outlook.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%F0%9F%91%8D-%E7%9B%B8%E5%85%B3%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">👍 相关视频教程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Hibernate-Validator"><span class="toc-number">2.</span> <span class="toc-text">Hibernate Validator</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3"><span class="toc-number">2.1.</span> <span class="toc-text">常用注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F"><span class="toc-number">2.2.</span> <span class="toc-text">使用方式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3"><span class="toc-number">2.3.</span> <span class="toc-text">自定义注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%98%E7%BC%BA%E7%82%B9"><span class="toc-number">2.4.</span> <span class="toc-text">优缺点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%A8%E5%B1%80%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86"><span class="toc-number">3.</span> <span class="toc-text">全局异常处理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%88%B0%E7%9A%84%E6%B3%A8%E8%A7%A3"><span class="toc-number">3.1.</span> <span class="toc-text">使用到的注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-1"><span class="toc-number">3.2.</span> <span class="toc-text">使用方式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%98%E7%BC%BA%E7%82%B9-1"><span class="toc-number">3.3.</span> <span class="toc-text">优缺点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">4.</span> <span class="toc-text">总结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80"><span class="toc-number">5.</span> <span class="toc-text">项目源码地址</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/c60470b9a892.html" title="Java集合使用注意事项总结">Java集合使用注意事项总结</a><time datetime="2024-02-03T04:58:22.000Z" title="发表于 2024-02-03 12:58:22">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/81fb7a201f29.html" title="无题">无题</a><time datetime="2024-02-03T03:15:31.812Z" title="发表于 2024-02-03 11:15:31">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/5737c1ec69a9.html" title="Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)">Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)</a><time datetime="2024-01-31T06:56:16.000Z" title="发表于 2024-01-31 14:56:16">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/f510db7d2f19.html" title="Spring常见面试题总结">Spring常见面试题总结</a><time datetime="2024-01-31T06:55:58.000Z" title="发表于 2024-01-31 14:55:58">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/9be065e9f288.html" title="redis 面试">redis 面试</a><time datetime="2024-01-31T06:55:55.000Z" title="发表于 2024-01-31 14:55:55">2024-01-31</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By 十一星野</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.staticfile.org/instant.page/5.2.0/instantpage.min.js" type="module"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div></body></html>